﻿Imports System.Runtime.InteropServices

Public Class NativeFuncs
    <DllImport("SSLLib")> _
    Public Shared Function ensureconnmgrready(ByVal pErrorString As Text.StringBuilder) As Integer
    End Function

    <DllImport("SSLLib")> _
    Public Shared Function enumerateconnections(ByVal pIndex As Integer, ByVal pDestinationInfo As Text.StringBuilder) As Integer
    End Function

    <DllImport("SSLLib")> _
    Public Shared Function ensureconnected(ByVal pErrorString As Text.StringBuilder, ByVal pHostName As String, ByVal pUseSpecific As Boolean, ByVal pSpecificNetwork As Integer) As Integer
    End Function

    Public Enum CSIDL
        CSIDL_DESKTOP = 0
        CSIDL_PROGRAMS = 2
        CSIDL_PERSONAL = 5
        CSIDL_FAVORITES_GRYPHON = 6
        CSIDL_STARTUP = 7
        CSIDL_APPDATA = 26
    End Enum

    <DllImport("coredll.dll")> _
    Public Shared Function SHGetSpecialFolderPath(ByVal hwndOwner As IntPtr, ByVal lpszPath As Text.StringBuilder, ByVal nFolder As CSIDL, ByVal fCreate As Boolean) As Boolean
    End Function
End Class

Public Class ConnectionsEnumerator
    Public Shared Function GetAvailableConnections() As Generic.List(Of String)
        Dim _availableDestinations As New Generic.List(Of String)
        Dim _conmgrReady As Boolean = False
        _conmgrReady = EnsureConnMgrReady()

        If _conmgrReady Then
            Dim _i As Integer = 0
            While True
                Dim _destInfo As New Text.StringBuilder(1024)
                Dim _res As Integer = NativeFuncs.enumerateconnections(_i, _destInfo)
                If _res = -1 Then
                    Exit While
                End If
                _availableDestinations.Add(_destInfo.ToString)
                _i += 1
            End While
        End If

        Return _availableDestinations
    End Function

    Public Shared Function EnsureConnMgrReady() As Boolean
        Dim _errorBuffer As New Text.StringBuilder(1024)
        If NativeFuncs.ensureconnmgrready(_errorBuffer) = -1 Then
            Trace.WriteLine("connection manager is not ready, continuing anyway. " & _errorBuffer.ToString)
            Return False
        Else
            Return True
        End If
    End Function
End Class
